//
//  UIImage + Extension.swift
//  microBlog
//
//  Created by apple on 16/4/25.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit

extension UIImage {
    
    func scaleToWidth(width: CGFloat) -> UIImage {
        
        if self.size.width < width {
            
            return self
        }
        
        let height = self.size.height * width / self.size.width
        
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        
//        开启指定大小上下文
        UIGraphicsBeginImageContext(rect.size)
//        将内容画到指定的尺寸中
        self.drawInRect(rect)
//        取得图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
//        关闭图形上下文
        UIGraphicsEndImageContext()
        
        return image
    }
    
    class func getScreenShot() -> UIImage {
        
        let window = UIApplication.sharedApplication().keyWindow!
        
        let rect = window.frame
        
        // 开启图形上下文
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        // 将图形渲染到上下文中
        window.drawViewHierarchyInRect(rect, afterScreenUpdates: false)
        // 获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭图形上下文
        UIGraphicsEndImageContext()
        
        return image
        
    }
}
